package com.mezz.bones.im.gateway.handler;

import cn.hutool.core.util.StrUtil;
import com.mezz.bones.im.common.domain.dto.ApplicationDto;
import com.mezz.bones.im.common.exception.ImBaseException;
import com.mezz.bones.im.common.result.ImResultCode;
import com.mezz.bones.im.common.service.IApplicationService;
import com.mezz.bones.im.gateway.manager.AppidManager;
import io.netty.channel.ChannelHandler;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.handler.codec.http.FullHttpRequest;
import io.netty.handler.codec.http.QueryStringDecoder;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import java.util.List;

@Slf4j
@Component
@ChannelHandler.Sharable
@AllArgsConstructor
public class AppIdParamHandler extends ChannelInboundHandlerAdapter {

    private final AppidManager appidManager;
    private final IApplicationService applicationService;

    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        if (msg instanceof FullHttpRequest) {
            FullHttpRequest request = (FullHttpRequest) msg;
            String uri = request.uri();
            
            // 解析URL参数
            QueryStringDecoder queryDecoder = new QueryStringDecoder(uri);
            List<String> appIds = queryDecoder.parameters().get("appid");
            
            if (appIds != null && !appIds.isEmpty()) {
                String appId = appIds.get(0);

                //校验appid
                ApplicationDto applicationDto = applicationService.getByAppId();
                if(!applicationDto.getAppId().equals(appId)){
                    throw new ImBaseException(ImResultCode.SYS_ERROR,"appid不存在");
                }

                // 保存appId到Channel属性中
                appidManager.setAppid(ctx,appId);
                
                // 移除URL中的参数部分，只保留路径
                String path = queryDecoder.path();
                if (StrUtil.isNotBlank(path)) {
                    request.setUri(path);
                }
                
                log.debug("解析到appId参数: {}", appId);
            } else {
                log.error("未找到appId参数, uri: {}", uri);
                throw new ImBaseException(ImResultCode.SYS_ERROR,"未找到appid参数");
            }
        }
        
        // 传递给下一个handler
        ctx.fireChannelRead(msg);
    }
}